<?php

/*
	info: MySQL数据库连接
	date: 2011-12-19
*/

if (!defined('WEBINROOT'))
{
	header("HTTP/1.0 404 Not Found");
	exit();
}

if (defined('MYSQL_CLASS'))
{
	return;
}
define('MYSQL_CLASS', TRUE);

class MysqlDB
{
	public $querynum = 0;
	public $queryinfo = '';
	private $link;

	public function Connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0)
	{
		if ($pconnect)
		{
			if (!$this->link = @mysql_pconnect($dbhost, $dbuser, $dbpw))
			{
				$this->Halt('Can not connect to Database server');
			}
		}
		else
		{
			if (!$this->link = @mysql_connect($dbhost, $dbuser, $dbpw, 1))
			{
				$this->Halt('Can not connect to Database server');
			}
		}

		if ($this->Version() > '4.1')
		{
			global $webconfig;
			$tempServerSet = '';
			if ($webconfig['dbcharset'])
			{
				$tempServerSet .= "character_set_connection={$webconfig['dbcharset']}, character_set_results={$webconfig['dbcharset']}, character_set_client=binary";
			}

			if (defined('WEBTIMEZONE'))
			{
				$temptimenum = intval(WEBTIMEZONE);
				$temptimestr = ($temptimenum >= 0) ? "+{$temptimenum}:00" : "{$temptimenum}:00";
				$tempServerSet .= (empty($tempServerSet) ? '' : ', ')."time_zone='{$temptimestr}'";
			}

			if ($this->Version() > '5.0.1')
			{
				$tempServerSet .= (empty($tempServerSet) ? '' : ', ')."sql_mode=''";
			}

			if (!empty($tempServerSet))
			{
				mysql_query("SET {$tempServerSet}", $this->link);
			}
		}

		if ($dbname)
		{
			mysql_select_db($dbname, $this->link);
		}
	}

	public function SelectDB($dbname)
	{
		return mysql_select_db($dbname, $this->link);
	}

	public function FetchArray($query, $result_type = MYSQL_ASSOC)
	{
		return mysql_fetch_array($query, $result_type);
	}

	public function Query($sql, $type = '')
	{
		if (WEBDEBUG)
		{
			$beginmtime = explode(' ', microtime());
		}

		$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ?
			'mysql_unbuffered_query' : 'mysql_query';
		if (!($query = $func($sql, $this->link)) && $type != 'SILENT')
		{
			$this->Halt('SQL Query Error', $sql);
		}
		$this->querynum++;

		if (WEBDEBUG)
		{
			$endmtime = explode(' ', microtime());
			$costtime = number_format(($endmtime[1]+$endmtime[0]-$beginmtime[1]-$beginmtime[0]), 6);
			$this->queryinfo .= '<hr />['.$this->querynum.'] '.htmlspecialchars($sql).' <span style="color: red">'."({$costtime} seconds)</span>\n";
		}

		return $query;
	}

	public function AffectedRows()
	{
		return mysql_affected_rows($this->link);
	}

	public function Error()
	{
		return (($this->link) ? mysql_error($this->link) : mysql_error());
	}

	public function Errno()
	{
		return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
	}

	public function Result($query, $row = 0)
	{
		$query = @mysql_result($query, $row);
		return $query;
	}

	public function NumRows($query)
	{
		$query = mysql_num_rows($query);
		return $query;
	}

	public function NumFields($query)
	{
		return mysql_num_fields($query);
	}

	public function FreeResult($query)
	{
		return mysql_free_result($query);
	}

	public function InsertId()
	{
		return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->Result($this->Query("SELECT last_insert_id()"), 0);
	}

	public function FetchRow($query)
	{
		$query = mysql_fetch_row($query);
		return $query;
	}

	public function FetchFields($query)
	{
		return mysql_fetch_field($query);
	}

	public function Version()
	{
		return mysql_get_server_info($this->link);
	}

	public function Close()
	{
		return mysql_close($this->link);
	}

	public function Halt($message = '', $sql = '')
	{
		$msg = '';
		if ($message)
		{
			$msg = '<strong>MSG</strong>:<br />'.$message.'<br />';
		}
		if ($sql && WEBDEBUG)
		{
			$msg .= '<strong>SQL</strong>:<br />'.$sql.'<br />';
			$msg .= '<strong>TIP</strong>:<br />'.$this->Error();
		}
		echo $msg;
		exit();
	}

	/**
	 * 生成用于SQL条件或者写入的语句
	 * @param $mixVar 数组
	 * @return string 用于sql中的字符串
	 */
	public function BuildFieldSql($mixVar, $strGlue = ',')
	{
		$tempOutSql = '';
		if (is_array($mixVar))
		{
			$tempsqlarray = array();
			foreach ($mixVar as $tempKey => $tempValue)
			{
				$tempsqlarray[] = "`{$tempKey}`='{$tempValue}'";
			}
			$tempOutSql = implode($strGlue, $tempsqlarray);
		}
		else
		{
			$tempOutSql = $mixVar;
		}
		return $tempOutSql;
	}

	/**
	 * 生成用于SQL IN查询的语句
	 * @param $mixVar 用于in的条件，“,”隔开的字符串或者数组
	 * @return string 放入in中的字符串
	 */
	public function BuildInSql($mixVar)
	{
		$tempOutSql = '';
		if (!is_array($mixVar))
		{
			$mixVar = explode(',', $mixVar);
		}
		$mixVar = array_diff(array_unique($mixVar), array(''));
		if (count($mixVar) > 0)
		{
			$tempOutSql = "'".implode("','", $mixVar)."'";
		}
		return $tempOutSql;
	}

	/**
	 * 生成用于多项搜索的SQL语句
	 * @param $strSearch 搜索条件，多个用空格隔开
	 * @param $aryField 要搜索的字段
	 * @return string 用于sql中的字符串
	 */
	public function BuildSearchSql($strSearch, $aryField)
	{
		$tempOutSql = "";
		$tempSql = "";
		if (trim($strSearch)!='' && count($aryField)>0)
		{
			$tempStrSearchArray = explode(' ', $strSearch);
			foreach ($tempStrSearchArray as $tempStr)
			{
				$tempStr = trim($tempStr);
				if ($tempStr != '')
				{
					foreach ($aryField as $tempfield)
					{
						if ($tempSql != '')
						{
							$tempSql .= " OR ";
						}
						$tempfieldformat = strpos($tempfield, '.') ? $tempfield : "`{$tempfield}`";
						$tempSql .= "{$tempfieldformat} LIKE '%{$tempStr}%'";
					}
					if ($tempOutSql != '')
					{
						$tempOutSql .= " AND ";
					}
					$tempOutSql .= "($tempSql)";
					$tempSql = "";
				}
			}
		}
		return $tempOutSql;
	}

	public function BuildTableName($strTable)
	{
		global $webconfig;
		if (substr($strTable, 0, strlen($webconfig['dbpre'])) != $webconfig['dbpre'])
		{
			$strTable = $webconfig['dbpre'].$strTable;
		}
		return $strTable;
	}

	/**
	 * 获取一个值 用于快速统计查询
	 * @param $strSql 要执行的sql语句
	 * @return mix 得到的结果
	 */
	public function GetNum($strSql)
	{
		return $this->Result($this->Query($strSql));
	}

	/**
	 * 获取一条记录
	 * @param $strSql 要执行的sql语句
	 * @return array 获取的内容数组
	 */
	public function GetOne($strSql)
	{
		return $this->FetchArray($this->Query($strSql));
	}

	/**
	 * 删除数据
	 * @param $strTable 表名
	 * @param $mixCondition 执行条件
	 * @param $intLimit 限制条数
	 * @return bool 是否成功
	 */
	public function Delete($strTable, $mixCondition, $intLimit = 0)
	{
		if ($strTable=='')
		{
			return FALSE;
		}
		$strCondition = $this->BuildFieldSql($mixCondition, ' AND ');
		$strTable = $this->BuildTableName($strTable);
		$tempWhereSql = ($strCondition != '') ? " WHERE {$strCondition}" : "";
		$tempLimitSql = ($intLimit > 0) ? " LIMIT {$intLimit}" : "";
		$tempResult = $this->Query("DELETE FROM {$strTable}{$tempWhereSql}{$tempLimitSql}");
		return $tempResult;
	}

	/**
	 * 插入新数据
	 * @param $strTable 表名
	 * @param $mixData 设定的值
	 * @param $isReturnId 是否返回插入ID
	 * @param $isReplace 是否采用replace方式
	 * @return bool 是否成功或者ID值
	 */
	public function Insert($strTable, $mixData = '', $isReturnId = FALSE, $isReplace = FALSE)
	{
		global $webglobal;
		if (empty($mixData) && !empty($webglobal['CPD']))
		{
			$mixData = $webglobal['CPD'];
		}
		$strData = $this->BuildFieldSql($mixData);
		if ($strTable=='' || $strData=='')
		{
			return FALSE;
		}
		$strTable = $this->BuildTableName($strTable);
		$strCmd = $isReplace ? 'REPLACE INTO' : 'INSERT INTO';
		$tempResult = $this->Query("{$strCmd} {$strTable} SET {$strData}");
		return ($tempResult && $isReturnId) ? $this->InsertId() : $tempResult;
	}

	/**
	 * 更新数据
	 * @param $strTable 表名
	 * @param $mixData 设定的值
	 * @param $mixCondition 执行条件
	 * @return bool 是否成功
	 */
	public function Update($strTable, $mixData = '', $mixCondition = '')
	{
		global $webglobal;
		if (empty($mixData) && !empty($webglobal['CPD']))
		{
			$mixData = $webglobal['CPD'];
		}
		$strData = $this->BuildFieldSql($mixData);
		$strCondition = $this->BuildFieldSql($mixCondition, ' AND ');
		if ($strTable=='' || $strData=='')
		{
			return FALSE;
		}
		$strTable = $this->BuildTableName($strTable);
		$tempWhereSql = ($strCondition != '') ? " WHERE {$strCondition}" : "";
		$tempResult = $this->Query("UPDATE {$strTable} SET {$strData}{$tempWhereSql}");
		return $tempResult;
	}

}	//end class
